import express from "express";
import db from "../db/db.js";
import { arrayTranslate } from "../common/arrayTranslate.js";

const getCurFundInfo = express.Router();

const getAllFundNames = async () => {
    return new Promise((resolve, reject) => {
        const sql = `
        SELECT a.* FROM asset a JOIN (
    SELECT fundName, MAX(date) AS latest_date
    FROM asset
    WHERE fundName IS NOT NULL AND principal > 0
    GROUP BY fundName
) AS latest_assets ON a.fundName = latest_assets.fundName AND a.date = latest_assets.latest_date;
`;
        db.query(sql, (err, results) => {
            if (err) {
                return reject(err);
            }
            resolve(results);
        });
    });
};

getCurFundInfo.get("/getCurFund", async (req, res) => {
    try {
        const dataRes: any = await getAllFundNames();
        res.send({
            code: 200,
            message: "获取当前持有基金情况 请求成功！",
            result: dataRes,
        });
    } catch (error) {
        console.error("Error fetching file records:", error);
        res.status(500).send({
            code: 1,
            message: "获取当前持有基金情况 请求失败！",
            result: null,
        });
    }
});

export default getCurFundInfo;
